package com.abvnet.project.water.api;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URI;
import java.util.List;
import java.util.Map;

public class Client {

    private static final String url = "http://10.6.2.133:8088";

    private static CloseableHttpClient httpClient = HttpClients.createDefault();

//	private static final String privateKey =
// "MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBAKN+dfp+tg0F8SPFHJ7gka8COI7VyQFZUP7hlvhE5XZ8D7A9+qQY1ZtU4V
// /daPPoX2NH4eF0r3JQuvy9Vm7NFNt1RsaTUX/PpscX7xK8CsU/mgzGZ/M3pro7UuStgG4ezCdL8ZWtoI9iMVjTRBLMsJlRZo3RbC4TFqgRyD+ud08tAgMBAAECgYEAhrU1o
// /UvLr/MlbpdAJLrthTQYO/ItDHRSJC7AUhTADLsAjyu/PHxXhCruX8GcKDvpy+c71RjEn9t8bxXMOgM3Av4a7yphdlTg4Ew
// +lKL8JBBs9MREWOWRch0TRrA7wP15rQYdphKrp9T+xWk3YqdphWKmsvOF2iTlCl2LOGIxYkCQQDU74iZTTQNyEEJVJl6TER02cPZ1kBL1OjKBooRjJsrRwlwOU7BcIWZKo
// /k3WpApRTMaJnmIu1XhtXeSZj3q1R/AkEAxI8l+4JJwKsGHYaJIbQsD7h/+NMtpDR166RWhHwWqo
// /6y2L3OWbR5jfcY8bf2PmVjX5y8fxPv6wXqP3z41gWUwJBAMmKhpIDHrfEyLnaFwJIWar3yoXOYkDkHgnJsrj1ipClxeswcrholirovBV09HKHTW5Duxa2DEsB1j91DZGt2mUCQEXhrttQYvBA3Ze5sR9ucwvTyIuqaNusWxBACRJpG5XgQoX01Xhu+ckjqxM+LW9yrJz1i+BEmAXJJVBLmV4Gf0kCQQCCQ89qUqoAuRgqnfcEXGo9AYZLMciGPm+T0UQB4tdehV8YwdhFZ5dHgElu2gWVv8Vs4gUB2jN2k34oOE69zjxk";
	
	/*public static String sign(String payload) throws Exception {
		JwtBuilder builder = Jwts.builder().setHeaderParam("typ", "JWT").setHeaderParam("alg", "RS256").setPayload(payload).signWith
		(SignatureAlgorithm.RS256, getPrivateKey(privateKey));
        return builder.compact();
	}*/
	
	/*public static PublicKey getPublicKey(String key) throws Exception {
        byte[] keyBytes = Base64Encodes.decodeBase64(key);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PublicKey publicKey = keyFactory.generatePublic(keySpec);
        return publicKey;
	}*/
	
	/*public static PrivateKey getPrivateKey(String key) throws Exception {
		byte[] keyBytes = Base64Encodes.decodeBase64(key);
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
        return privateKey;
	}*/

    public static void getRequest(String uri, Map<String, String> map) {
        HttpGet get = new HttpGet(url + uri);
        List<NameValuePair> params = Lists.newArrayList();
        for (Map.Entry<String, String> entry : map.entrySet()) {
            params.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }
        CloseableHttpResponse response = null;
        try {
            String str = EntityUtils.toString(new UrlEncodedFormEntity(params, "UTF-8"));
            get.setURI(new URI(get.getURI().toString() + "?" + str));
            response = httpClient.execute(get);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == HttpStatus.SC_OK) {
                HttpEntity entity = response.getEntity();
                String jsonStr = EntityUtils.toString(response.getEntity());
//				String s = GZIPUtils.uncompress(Base64Encodes.decodeBase64(jsonStr));
//				System.out.println("加密字符串: "+jsonStr);
//				System.out.println("加密字符串长度: "+jsonStr.length());
                System.out.println("原始字符串: " + jsonStr);
//				System.out.println("原始字符串长度: "+jsonStr.length());
                EntityUtils.consume(entity);
            } else {
                System.out.println("api接口调用失败, HttpStatus: " + statusCode);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void postRequest(String uri, Map<String, String> map) {
        HttpPost post = new HttpPost(url + uri);
        List<NameValuePair> params = Lists.newArrayList();
        for (Map.Entry<String, String> entry : map.entrySet()) {
            params.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }
        CloseableHttpResponse response = null;
        try {
            post.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
            response = httpClient.execute(post);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == HttpStatus.SC_OK) {
                HttpEntity entity = response.getEntity();
                String jsonStr = EntityUtils.toString(entity);
//				String s = GZIPUtils.uncompress(Base64Encodes.decodeBase64(jsonStr));
//				System.out.println("加密字符串: "+jsonStr);
//				System.out.println("加密字符串长度: "+jsonStr.length());
                System.out.println("原始字符串: " + jsonStr);
//				System.out.println("原始字符串长度: "+s.length());
                EntityUtils.consume(entity);
            } else {
                System.out.println("api接口调用失败, HttpStatus: " + statusCode);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) throws Exception {
        Map<String, String> map = Maps.newHashMap();
		/*map.put("mtType", "4");
		map.put("productId", "E1000011");
		map.put("programId", "1");
		String payload = JsonMapper.toJsonString(map);
		String token = sign(payload);
		System.out.println("token: "+token);*/
		
		/*map.put("userName", "xiaoming");
		map.put("pwd", StringUtils.encryptString("1234"));
		String payload = JsonMapper.toJsonString(map);
		System.out.println(payload);
		System.out.println(payload.length());
		String token = JwtToken.sign(payload);
		System.out.println(token);
		Jws<Claims> jws = JwtToken.getClaimsJws(token);
		String body = JwtToken.getBodyJsonString(jws);
		System.out.println(body);
		System.out.println(body.length());
		System.out.println(JwtToken.sign(body));
		map.clear();*/

//        getRequest("/api/project/list", map);
//		map.put("pageNum","0");
//		map.put("pageSize","10");
//		getRequest("/api/microbial/list", map);
//		map.clear();

//        getRequest("/api/microbial/datas", map);
//        map.clear();

//        map.put("projectId", "7");
//        getRequest("/api/project/water/get", map);
//        map.clear();

//        getRequest("/api/sewage/plan/list",map);

//        map.put("planId", "2");
//        getRequest("/api/sewage/plan/get",map);

//        map.put("projectId", "7");
//        getRequest("/api/sewage/flow/list",map);

//        map.put("projectId", "7");
//        getRequest("/api/project/plan/list",map);

        map.put("parentId", "106");
        getRequest("/api/project/getCustomer",map);

//        map.put("projectId", "7");
//        getRequest("/api/project/summary",map);

//        map.put("projectId", "1");
//        getRequest("/api/project/eval/get",map);

//        getRequest("/api/contact/get",map);

//        getRequest("/api/project/area",map);
//        getRequest("/api/project/industry",map);

//        map.put("projectId", "7");
//        map.put("commentUserId", "3");
//        getRequest("/api/project/comment/list",map);

//        map.put("waterId", "12");
//        map.put("rawCod", "1500");
//        postRequest("/api/project/water/edit",map);

//      getRequest("/api/project/list", map);
//      map.clear();

//      map.put("projectId", "2");
//      getRequest("/api/project/tech/get", map);
//      map.clear();

//        map.put("projectId", "7");
//        getRequest("/api/project/progress/list", map);
//        map.clear();

//        map.put("projectId", "1");
//        getRequest("/api/project/data/water", map);
//        getRequest("/api/project/data/micro", map);

        /*map.put("username", "duj");
        map.put("password", "123456");
        postRequest("/api/login",map);
        map.clear();*/

		/*System.out.println("开始时间: "+DateUtils.getDateTime());
		long s = System.currentTimeMillis();
		for(int i=0;i<25;i++) {
			for(int j = 1;j<9;j++) {
				map.put("programId", String.valueOf(j));
				String payload = JsonMapper.toJsonString(map);
				map.put("token", sign(payload));
				postRequest("/api/live/stb/epg", map);
				map.clear();
			}
		}
		System.out.println("结束时间: "+DateUtils.getDateTime());
		System.out.println("耗时: "+(System.currentTimeMillis()-s)+" 毫秒");*/

		/*map.put("programId", "101");
		String payload = JsonMapper.toJsonString(map);
		map.put("token", sign(payload));
		postRequest("/api/live/stb/epg", map);*/
//        String path = "C:/abvfile/flow/2019/08/15/60cb02ce82688ea21a5722f938c03532.png";
//        System.out.println(path);
//        FileUtils.deleteFile(path);

        /*String data = "{\"nodes\":[{\"nodeId\":\"noderaw\",\"nodeText\":\"污水\",\"positionX\":328,\"positionY\":48}," +
                "{\"nodeId\":\"node5\",\"nodeText\":\"细格栅\",\"positionX\":328,\"positionY\":176}," +
                "{\"nodeId\":\"node11\",\"nodeText\":\"厌氧池\",\"positionX\":328,\"positionY\":297}]," +
                "\"connections\":[{\"uuids\":[\"noderawBottomCenter\",\"node5TopCenter\"]}," +
                "{\"uuids\":[\"node5BottomCenter\",\"node11TopCenter\"]}]}";
        System.out.println(data.length());
        data = Base64.encodeBase64String(GZIPUtils.compress(data));
        System.out.println(data);
        System.out.println(data.length());*/

//        System.out.println(BigDecimal.valueOf(5*100).divide(BigDecimal.valueOf(9), HALF_UP).intValue());
    }
}
